<?php
class SiteController extends Controller
{
	private $_initialized = false;
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array (
		// captcha action renders the CAPTCHA image displayed on the
		// contact page
				'captcha' => array (
						'class' => 'CCaptchaAction','backColor' => 0xFFFFFF 
		),
		// page action renders "static" pages stored under
		// 'protected/views/site/pages'
		// They can be accessed via: index.php?r=site/page&view=FileName
				'page' => array (
						'class' => 'CViewAction' 
						)
						);
	}
	/**
	 * {PageCache}
	 * 控制器：可以使用COutputCache类作为一个我们控制器类中的一个行为过滤器
	 *
	 * COutputCache来缓存数据时，来作为自动生成key名字的策略。下面是可以使用的一个列表： *
	 * varyByRoute：通过将该选项设置为true，具体请求的路由部分将会作为独立标识符的一部分用于生成缓存数据。所以，你可以使用请求controller和acion的组合来区别缓存内容。
	 * varyBySession：通过设置该选项为true，将使用唯一的session
	 * id来区分缓存中的内容。每个用户的session都是不同的，但是可以用来为缓存服务。
	 * varyByParam：如前面所说，这里是用输入的GET中的参数来区分缓存内容。
	 * varyByExpression：给该选项设置PHP表达式，我们可以使用相应表达式的结果来区分缓存的内容。
	 * 还有要注意的是 COutputCache默认的cacheid是cache
	 * http://yiiblog.info/blog/2011/04/cache-in-yii-code-demo/
	 *
	 * public function filters()
	 * {
	 * return array(
	 * array('COutputCache + PageCache',
	 * 'duration'=>30,'varyByParam'=>array('id')),
	 * );
	 * }
	 * 使用('COutputCache + PageCache')PageCache缓存
	 *
	 * public function actionPageCache()
	 * {
	 * $this->render('pageCache');
	 * }
	 */
	public function filters()
	{
		return array (
		array (
						'COutputCache','duration' => 600,'varyByParam' => array (
								'id' 
								)
								)
								);
	}
	public function init()
	{
		// var_dump(Yii::app()->db);
		$this->_initialized = true;
		if ($this->hasEventHandler ( 'onBeforeControllerInit' ))
		{
			$this->onBeforeControllerInit ( new CEvent ( $this ) );
		}
		// 获取不到：echo 'action:';print_r(Yii::app()->controller->action->id );
		// echo Yii::app()->controller->id;
		parent::init ();
	}
	/**
	 * 你只需要也停止jquery初始化两次。
	 * Yii::app()->getClientScript()->scriptMap = array('jquery.js' => false,
	 * 'jquery-ui.min.js' => false);
	 */
	/**
	 * 调用实例：调用$this->someHandler()方法
	 * Yii::app()->getController()->attachEventHandler('onBeforeControllerInit',
	 * array($this,'someHandler'));
	 */
	public function onBeforeControllerInit($event)
	{
		$this->raiseEvent ( 'onBeforeControllerInit', $event );
	}
	public function getIsInitialized()
	{
		return $this->_initialized;
	}
	protected function beforeAction($action)
	{
		// $controllerId = Yii::app()->controller->id;
		// or
		// $controllerId = $this->getId();
		return parent::beforeAction ( $action );
	}
	/*
	 * protected function afterAction() { // $actionId = $action->id; return
	 * true; }
	 */
	public function someHandler()
	{
		return $this->_initialized;
	}
	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		Yii::app()->db;
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		// var_dump(Yii::app()->db);
		//$this->render ( 'index' );
		//$url = 'http://flights.ctrip.com/international/';
		//$content = file_get_contents($url);
		$content = '';
		$dataurls = 'http://flights.ctrip.com/international/subPage/AjaxFlightCheapInfo.aspx?startCityName=BJS&endCityName=';
		echo 'xxx';
		for($i=1; $i<=5; $i++){
			break;
			// echo '<BR>'.$dataurls.$i;
			// $i=5;


			$content = '<table>'.file_get_contents($dataurls.$i).'</table>';

			preg_match_all('/<tr>.*?<\/tr>/is', $content, $matches);
			// echo '<pre>';
			// print_r($matches);

			$matche = $matches[0];
			$data = array();
			for ($k=0; $k < count($matche); $k++) {
				preg_match_all('/<td.*?>.*?<\/td>/is', $matche[$k], $matches);
				// print_r(current($matches));

				$matches = array_map('strip_tags', $matches[0]);
				//echo 'dddd';
				//print_r($matches);
				//die();
				$data[] = $matches;
			}

			//print_r($data);
			foreach ($data as $datarow){
				//print_r($datarow);
					
				$key = md5(join(',', $datarow));
				$sql = 'SELECT COUNT(*) as num FROM wdb_airport WHERE mdkey=\''.$key.'\'';
				$num = Yii::app()->db->createCommand($sql)->queryScalar();
				if ($num == false) {
					$sql = "insert into wdb_airport (startstation,transfer
					,endstation,expire,airway,other,roundtrip,price,mdkey)  values ('".$datarow[0]."','".$datarow[1]."','".$datarow[2]."','".$datarow[3]."','".$datarow[4]."','".$datarow[5]."','".$datarow[6]."','".$datarow[7]."','".$key."');";
					// echo '<br>'.$sql;
					$excute = Yii::app()->db->createCommand($sql)->execute();
					if ($excute) {

					}
				}
			}
		}

		// 酒店hotel
		$uri = 'http://pages.ctrip.com/commerce/promote/201303/hotel/jb/index4_1.html#ctm_ref= hi_sp_1_i';
		$imageurl = 'http://pages.ctrip.com/commerce/promote/201303/hotel/jb/';
		$content = file_get_contents($uri);
		// echo $content;

		preg_match_all('/<table.*?>(.+?)<\/table>/is', $content, $matches);

		//print_r($matches[0]);
		$subjects = $matches[0];
		$matches = array();
		for($i=0; $i<count($subjects);$i++){
			preg_match_all('/style1.*?>(.*?)<\/td>/is', $subjects[$i], $matches);

			$anchorsubject = next($matches);//print_r($anchorsubject);die();
			preg_match_all('/<a.*?>(.*?)<\/a>/is', $anchorsubject[0], $matches);
			
			$title = str_replace('&nbsp;', '',strip_tags( current($matches[1])));
			//print_r($title);
			//die();
			$matches = array();
			preg_match_all('/style1.*?>.*?<\/td>.*?<\/td>/is', $subjects[$i], $matches);


			//print_r(current($matches[0]));
			$imageSubject = current($matches[0]);
			$matches = array();
			preg_match_all('/<td.*?>(.*?)<\/td>/is', $imageSubject, $matches);
			current($matches);
			$next = next($matches);
			// echo "<BR><BR>\n";
			$nsubject = current($next);
				
			$matche = array();
			preg_match('/<img.*?([\w]+?\.[\w]+).*?>/is', $nsubject, $matche);print_r($matche);
			$filename = next($matche);
				
			// var_export($filename);
			preg_match('/src\s*?=.+?([\w\/]+?\.[\w]+)/', $matche[0], $dm);
			// fopen($filename, $mode)
			
			// echo $imageurl.$dm[1];
			// die();
			if ($imagecontent = file_get_contents($imageurl.$dm[1])){
				$path = './attchment/'.$filename;
				$result = file_put_contents($path, $imagecontent);
				// echo $imagecontent;die();
				$sql = "insert into wdb_hotel (title,path,filename) values ('".$title."','".$path."','".$filename."')";
					
				$execute = Yii::app()->db->createCommand($sql)->execute();
					
				echo '<br>'.$sql;
					
				//if ($execute) {
					
				//}
					
				//die();
			}
		}
	}
	public function actionMain()
	{
		// echo "<BR>actionMain()";
		// $this->render('main');
	}
	public function actionMeun()
	{
		// echo "<BR>actionMeun()";
		$this->render ( 'meund' );
	}
	public function actionHead()
	{
		// echo "<BR>actionHead()";
		// $this->render('main');
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
		if ($error = Yii::app ()->errorHandler->error)
		{
			if (Yii::app ()->request->isAjaxRequest)
			echo $error ['message'];
			else
			$this->render ( 'error', $error );
		}
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		$model = new ContactForm ();
		if (isset ( $_POST ['ContactForm'] ))
		{
			$model->attributes = $_POST ['ContactForm'];
			if ($model->validate ())
			{
				$name = '=?UTF-8?B?' . base64_encode ( $model->name ) . '?=';
				$subject = '=?UTF-8?B?' . base64_encode ( $model->subject ) . '?=';
				$headers = "From: $name <{$model->email}>\r\n" . "Reply-To: {$model->email}\r\n" . "MIME-Version: 1.0\r\n" . "Content-type: text/plain; charset=UTF-8";

				mail ( Yii::app ()->params ['adminEmail'], $subject, $model->body, $headers );
				Yii::app ()->user->setFlash ( 'contact', 'Thank you for contacting us. We will respond to you as soon as possible.' );
				$this->refresh ();
			}
		}
		$this->render ( 'contact', array (
				'model' => $model 
		) );
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$model = new LoginForm ();

		// if it is ajax validation request
		if (isset ( $_POST ['ajax'] ) && $_POST ['ajax'] === 'login-form')
		{
			echo CActiveForm::validate ( $model );
			Yii::app ()->end ();
		}

		// collect user input data
		if (isset ( $_POST ['LoginForm'] ))
		{
			$model->attributes = $_POST ['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if ($model->validate () && $model->login ())
			$this->redirect ( Yii::app ()->user->returnUrl );
		}
		// display the login form
		$this->render ( 'login', array (
				'model' => $model 
		) );
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app ()->user->logout ();
		$this->redirect ( Yii::app ()->homeUrl );
	}
	public function actionCSortAttributes()
	{
		$x = array (
				'*','consult.consulttime' => array (
						'asc' => 'consult.consulttime asc','desc' => 'consult.consulttime desc','label' => 'consult.consulttime' 
						),'consult.weekday' => array (
						'asc' => 'consult.weekday asc','desc' => 'consult.weekday desc','label' => 'consult.weekday' 
						),'consult.username' => array (
						'asc' => 'consult.username asc','desc' => 'consult.username desc','label' => 'consult.username' 
						),'consult.consultstatus' => array (
						'asc' => 'consult.consultstatus asc','desc' => 'consult.consultstatus desc','label' => 'repeat.consultstatus' 
						),'consult.productnames' => array (
						'asc' => 'consult.productnames asc','desc' => 'consult.productnames desc','label' => 'consult.productnames' 
						),'consult.familiarlevel' => array (
						'asc' => 'consult.familiarlevel asc','desc' => 'consult.familiarlevel desc','label' => 'repeat.familiarlevel' 
						),'consult.media' => array (
						'asc' => 'consult.media asc','desc' => 'consult.media desc','label' => 'repeat.media' 
						),'consult.repeat' => array (
						'asc' => 'consult.repeat asc','desc' => 'consult.repeat desc','label' => 'repeat.repeat' 
						),'consult.avild' => array (
						'asc' => 'consult.avild asc','desc' => 'consult.avild desc','label' => 'consult.avild' 
						)
						);

						$s = array (
				'a','name','consult.consulttime' 
				);
				// CVarDumper::dump ( $s );
				$re = $this->csortAttributes ( $s );
				// print_r($re);
				// echo CVarDumper::dumpAsString ($re,1, true);
	}
	public function csortAttributes($columns)
	{
		$attributes = array ();
		foreach ( $columns as $column )
		{
			if (strpos ( $column, '*' ) !== false && strlen ( $column ) == 1)
			{
				array_push ( $attributes, $column );
			} elseif (strpos ( $column, '.' ) === false)
			{
				array_push ( $attributes, $column );
			} elseif (preg_match ( "/[a-z]+?\.[a-z]+$/i", $column ))
			{
				$attributes [$column] = array (
						'asc' => $column . ' asc','desc' => $column . ' desc','label' => $column 
				);
			}
		}
		return $attributes;
	}
}